import React, { useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { Toast } from 'antd-mobile'
import { useDispatch } from 'react-redux'
import { setinfo } from '../../store/Info'
import { getUserRole } from '../../utils/permission'
import './AuthCallback.css'

function GiteeCallback() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const dispatch = useDispatch()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // Gitee OAuth配置
  const GITEE_CONFIG = {
    clientId: 'fb2428e600444232b42e6e440fa526a268a93e12daa6ab0bea2f938b47cdcfb6',
    clientSecret: 'a97b39759b9682209bac55f479fbef559dd053775d678af162147df8b014a2d6',
    redirectUri: `${window.location.origin}/auth/gitee/callback`
  }

  useEffect(() => {
    const handleCallback = async () => {
      try {
        // 获取URL中的授权码和状态参数
        const code = searchParams.get('code')
        const state = searchParams.get('state')
        const error = searchParams.get('error')

        // 检查是否有错误
        if (error) {
          setError('授权失败，用户拒绝了授权请求')
          setLoading(false)
          return
        }

        // 检查是否有授权码
        if (!code) {
          setError('未获取到授权码')
          setLoading(false)
          return
        }

        console.log('Gitee授权码:', code)
        console.log('Gitee状态:', state)

        // 使用授权码换取访问令牌
        const tokenResponse = await fetch('https://gitee.com/oauth/token', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            grant_type: 'authorization_code',
            client_id: GITEE_CONFIG.clientId,
            client_secret: GITEE_CONFIG.clientSecret,
            code: code,
            redirect_uri: GITEE_CONFIG.redirectUri
          })
        })

        if (!tokenResponse.ok) {
          throw new Error('获取访问令牌失败')
        }

        const tokenData = await tokenResponse.json()
        const accessToken = tokenData.access_token

        if (!accessToken) {
          throw new Error('未获取到访问令牌')
        }

        // 使用访问令牌获取用户信息
        const userResponse = await fetch('https://gitee.com/api/v5/user', {
          headers: {
            'Authorization': `token ${accessToken}`
          }
        })

        if (!userResponse.ok) {
          throw new Error('获取用户信息失败')
        }

        const userData = await userResponse.json()
        console.log('Gitee用户信息:', userData)

        // 构建登录成功数据
        const loginData = {
          status: '0000',
          result: {
            sessionId: 'gitee_session_' + Date.now(),
            userId: userData.id || 'gitee_user_' + Date.now(),
            email: userData.email || userData.login + '@gitee.com',
            userName: userData.name || userData.login
          }
        }

        const data = loginData

        if (data && data.status === '0000') {
          const result = data.result || {}
          
          // 保存登录信息到本地存储
          if (result.sessionId) {
            localStorage.setItem('token', result.sessionId)
            localStorage.setItem('sessionId', result.sessionId)
          }
          
          if (result.userId) {
            localStorage.setItem('userId', String(result.userId))
          }
          
          // 保存用户信息
          const userEmail = result.email
          if (userEmail) {
            localStorage.setItem('email', userEmail)
          }
          
          if (result.userName) {
            localStorage.setItem('userName', result.userName)
          }
          
          // 获取用户角色
          const userRole = getUserRole(userEmail)
          localStorage.setItem('userRole', userRole)
          
          // 更新Redux状态
          dispatch(setinfo({
            email: userEmail || '',
            userId: result.userId || '',
            userName: result.userName || '',
            role: userRole
          }))
          
          Toast.show('Gitee登录成功！')
          
          // 跳转到首页
          navigate('/')
        } else {
          setError('Gitee登录失败')
          setLoading(false)
        }
      } catch (error) {
        console.error('Gitee登录错误:', error)
        setError('登录过程中发生错误，请稍后重试')
        setLoading(false)
      }
    }

    handleCallback()
  }, [searchParams, navigate, dispatch])

  if (loading) {
    return (
      <div className="auth-callback-container">
        <div className="loading-content">
          <div className="loading-spinner"></div>
          <p>正在处理Gitee登录...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="auth-callback-container">
        <div className="error-content">
          <div className="error-icon">❌</div>
          <h3>登录失败</h3>
          <p>{error}</p>
          <button 
            className="retry-button"
            onClick={() => navigate('/login')}
          >
            返回登录页
          </button>
        </div>
      </div>
    )
  }

  return null
}

export default GiteeCallback
